import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_common_app/event_bus/audio_bottom_event.dart';
import 'package:flutter_common_app/event_bus/global_event_bus.dart';
import 'package:flutter_common_app/router/routes.dart';
import 'package:flutter_common_app/utils/common_util/log_util.dart';
import 'package:flutter_common_app/widgets/app_bar/custom_app_bar.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  final String url;

  const WebViewPage(
    this.url, {
    Key key,
  }) : super(key: key);

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  WebViewController _webViewController;

  String appBarTitle;

  @override
  void initState() {
    GlobalEventBus().bus.fire(AudioBottomEvent(false));

    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
    super.initState();
  }

  @override
  void dispose() {
    GlobalEventBus().bus.fire(AudioBottomEvent(true));
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        appBarTitle != null ? Text(appBarTitle) : CupertinoActivityIndicator(),
        leading: BackButton(
          onPressed: onBack,
        ),
      ),
      body: WebView(
        initialUrl: widget.url,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _webViewController = webViewController;
        },
        onProgress: (int progress) {
          print("WebView is loading (progress : $progress%)");
        },
        javascriptChannels: <JavascriptChannel>[
          JavascriptChannel(
              name: 'Toaster',
              onMessageReceived: (JavascriptMessage message) {
                //这里监听 js交互
              }),
        ].toSet(),
        navigationDelegate: (NavigationRequest request) {
          if (request.url.startsWith('https://www.youtube.com/')) {
            LogUtil.v('blocking navigation to $request}');
            return NavigationDecision.prevent;
          }
          LogUtil.v('allowing navigation to $request');
          return NavigationDecision.navigate;
        },
        onPageStarted: (String url) {
          LogUtil.v('Page started loading: $url');
        },
        onPageFinished: (String url) {
          LogUtil.v('Page finished loading: $url');

          _webViewController.getTitle().then((title) {
            setState(() {
              appBarTitle = title;
            });
          });
        },
        gestureNavigationEnabled: true,
      ),
    );
  }

  void onBack() async {
    if (await _webViewController.canGoBack() &&
        await _webViewController.currentUrl() != widget.url) {
      _webViewController.goBack();
    } else {
      Routes.pop(context);
    }
  }
}
